//
//  TTLog.m
//  YuchBox
//
//  Created by Ivan on 11-10-11.
//  Copyright 2011年 __MyCompanyName__. All rights reserved.
//

#import "TTLog.h"
#import "StreamPeer.h"
#import "SingletonClassGenerator.h"


static const char *TTLogLevelString[] = {"INFO", "WARN", "DEBUG", "ERROR", "FATAL"};

@implementation TTLog
SYNTHESIZE_SINGLETON_FOR_CLASS(TTLog);

+ (NSString *)getLogDictionaryPath
{
    NSArray *docmentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *docmentPath = [docmentPaths objectAtIndex:0];
    NSString *tmpDictPath = [NSString stringWithFormat:@"%@/Log", docmentPath];
    
    return tmpDictPath;
}

- (id)init
{
    self = [super init];
    if (self) {
        // Initialization code here.
    }
    
    return self;
}

- (id)initSingleton
{
    self = [super init];
    if (self) {
        NSString *logDictPath = [TTLog getLogDictionaryPath];
        NSFileManager *fileMgr = [NSFileManager defaultManager];        
        
        if (![fileMgr fileExistsAtPath:logDictPath]) {
            // create new folder
            NSError *error = [[NSError alloc] init];
            [fileMgr createDirectoryAtPath:logDictPath withIntermediateDirectories:YES attributes:nil error:&error];
            if (0 != [error code]) {
                TTLOGF_INFO(@"create dictionary <%@> error, code:%d",logDictPath, [error code]);
            }
            [error release];
        }
        
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"yyyyMMdd"];
        NSString *today = [dateFormatter stringFromDate:[NSDate dateWithTimeIntervalSinceNow:0]];
        [dateFormatter release];
        
        _logFilePath    = [NSString stringWithFormat:@"%@/%@.log", logDictPath, today];
        _logWriter      = [[NSOutputStream alloc] initToFileAtPath:_logFilePath append:YES];
        
        [_logWriter open];
    }
    return self;
}

- (void)dealloc
{
    [_logWriter close];
    [_logWriter release];
    [super dealloc];
}

- (void)TTLog:(NSString *)log 
     logLevel:(TTLogLevel)type 
   TT__FILE__:(const char *)TT__FILE__ TT__FUNCTION__:(const char *)TT__FUNCTION__ TT__LINE__:(int)TT__LINE__
{
    @synchronized(_logWriter) {
        if (_logWriter != nil) {
            if ([_logWriter hasSpaceAvailable]) {
                // log datetime
                NSDateFormatter *dataFormatter = [[NSDateFormatter alloc] init];
                [dataFormatter setDateFormat:@"yyyy-MM-dd hh:mm:ss"];
                NSString *now = [dataFormatter stringFromDate:[NSDate dateWithTimeIntervalSinceNow:0]];
                [dataFormatter release];
                [_logWriter write:(const UInt8 *)[now UTF8String] maxLength:now.length];
                
                // log level
                NSString *logLevel = [NSString stringWithFormat:@"[%s]", TTLogLevelString[type]];
                [_logWriter write:(const UInt8 *)[logLevel UTF8String] maxLength:logLevel.length];
                
                // log content
                [_logWriter write:(const UInt8 *)[log UTF8String] maxLength:log.length];
                
                NSString *threadInfo = [NSString stringWithFormat:@" <%d:%@, %s:%d>",getpid(), [[NSThread currentThread] name], TT__FUNCTION__, TT__LINE__];
                [_logWriter write:(const UInt8 *)[threadInfo UTF8String] maxLength:threadInfo.length];
                
                NSLog(@"%@%@%@", logLevel, log, threadInfo);
                
                // return char
                const unsigned char returnChar[] = "\n";
                [_logWriter write:returnChar maxLength:1];
            }
        } else {
            NSLog(@"failed to log!");
        }
    }
    
}

+ (void)TTDataDump:(UInt8 *)data len:(NSInteger)len
{
//    printf("\n--------------------------------------------------");
    printf("\nBUFF LEN = %d\n", len);
    for (int i = 0; i < len ; i++) {
        if ((i%16)==0 && i != 0) {
            printf("\n");
        }
        printf("%02x ", data[i]);
    }
    
}
@end
